#Arduino Tester code to check for replies

#Import python libraries
import sys, math, time, string, os

def serial_listen(ser):
	command = ""
	if ser.inWaiting() >= 8:				#We have at least 1 command in the pipeline
		command = ser.read(8)   			#Read the cmd (8 bytes) 
	return command						#Return result
	
#Print a welcome message!
print "Arduino Serial Test Unit, Rev 0.1a"
print "-----------------------------------------------"
print "Revision date: 5/13/2011"

#Setup PySerial
import serial   

#Setup the serial port
port = 0
while(port < 5):
	try:
		print 'Contacting /dev/ttyUSB' + str(port) + '....'
		ser = serial.Serial('/dev/ttyUSB' + str(port))
		break
	except serial.serialutil.SerialException:
		print "Invalid Serial port!"
		port = port + 1

#Close down the script if no port is found at all
if(port == 5):
	print "No serial port found!"
	sys.exit()
else:
	print 'Connnected to serial port ttyUSB' + str(port)

#Ask for user input
while 1:
	input = raw_input('Please input an 8 byte command: ')
	print "Sending: " + input
	print "Listening to Arduino Response (Timeout @ 5 second)"
	ser.write(input)
	timeout = time.time()
	while time.time() - timeout < 5: #Try to get a response until timeout
		cmd = serial_listen(ser)
		if cmd != "":
			print "Serial command received: " + cmd			#Check if we have a command in the pipe
			instr = cmd[:4]						#Parse out the instruction
			param = cmd[4:]						#Parse out the parameters	
			timeout = timeout - 5				#Finish the loop